<template>
  <div class="invoice-record-page">
    <h2>发票记录</h2>
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" label-width="auto" inline>


        <el-form-item label="开票日期：" prop="inDateRange">
          <el-date-picker v-model="inDateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 390px;" @change="handleInvoiceDateChange" value-format="YYYY-MM-DD" />
        </el-form-item>


        <el-form-item label="单据日期：" prop="dateRange">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 390px;" @change="handleSlipDateChange" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item label="单据编号：">
          <el-input v-model="searchForm.salesSlipCode" placeholder="单据编号" clearable style="width: 200px;" />
        </el-form-item>

        <el-form-item label="客户：">
          <el-input v-model="searchForm.customerCode" placeholder="点击选择客户" @click="openCustomerDialog" readonly
            style="width: 200px;" />
          <CustomerDialog v-model="customerDialogVisible" @confirm="handleSelectCustomer" />
        </el-form-item>


        <el-form-item label="销售员：" prop="workNumber">
          <el-select v-model="searchForm.workNumber" placeholder="请选择" clearable style="width: 160px;">
            <el-option v-for="salesPerson in salesPersonList" :key="salesPerson.id" :label="salesPerson.name"
              :value="salesPerson.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="订单类型:">
          <el-select v-model="searchForm.isReturn" placeholder="请选择" style="width: 200px;">
            <el-option label="销售单" :value="0" />
            <el-option label="销售退货单" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="selectInv">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button>导出</el-button>
      <el-button @click="batchDelete" :disabled="selectedRows.length === 0">删除</el-button>
    </div>

    <div style="clear: both;"></div>
    <!-- 主表格 -->
    <div class="table-container">
      <el-table :data="invoiceList" border stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" align="center" />

        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button size="mini" type="text" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>

        <el-table-column label="开票日期" prop="date" width="120" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.date) }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="登记日期" prop="registerDate" width="120" sortable /> -->
        <el-table-column label="发票号" prop="invoiceNumber" width="150" sortable />
        <el-table-column label="开票金额" prop="currentInvoiceAmount" width="120" sortable />
        <!-- <el-table-column label="发票抬头" prop="invoiceTitle" width="180" show-overflow-tooltip /> -->

        <el-table-column label="单据日期" prop="slipDate" width="120" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.slipDate) }}
          </template>
        </el-table-column>
        <el-table-column label="单据编号" prop="salesSlipCode" width="150" sortable />
        <el-table-column label="销售人员" prop="workNumber" width="120" />
        <el-table-column label="客户" prop="customerCode" width="120" />
        <el-table-column label="源制单人" prop="s.workNumber" width="120" />
        <!-- <el-table-column label="源单制单日期" prop="sourceDate" width="150" /> -->
        <el-table-column label="数量" prop="itemCount" width="80" sortable />
        <el-table-column label="金额" prop="salesAmount" width="120" sortable />
        <el-table-column label="税额" prop="taxAmount" width="120" sortable />
        <el-table-column label="价税合计" prop="slipPrice" width="120" sortable />
        <el-table-column label="已收款" prop="currentInvoiceAmount" width="120" sortable />
        <!-- <el-table-column label="收款状态" prop="status" width="120" sortable>
          <template #default="scope">
            <el-tag :type="scope.row.status === '3' ? 'success' : scope.row.status === '1' ? 'warning' : 'danger'"
              size="small">
              {{ getPaymentStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="开票备注" prop="remarks" width="180" show-overflow-tooltip />
      </el-table>
    </div>

    <!-- 分页 -->
    <div style="float: right; padding-top: 20px;">
      <el-pagination background layout="prev, pager, next,jumper" :total="pageInfo.total" :page-size="pageInfo.pageSize"
        :current-page="pageInfo.pageNum" @current-change="changePage" />
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import CustomerDialog from '@/util/CustomerDialog.vue'

// 客户显示名称
const selectedCustomerDisplay = ref('')

// 表单数据
const searchForm = reactive({
  start_date: '',
  end_date: '',
  slipStart_date: '',
  slipEnd_date: '',
  salesSlipCode: '',
  customerCode: '',
  workNumber: '',
  isReturn: 0,
})
const dateRange = ref([])
const inDateRange = ref([])
// 处理日期变化
const handleInvoiceDateChange = (val) => {
  if (val && val.length === 2) {
    searchForm.start_date = val[0]
    searchForm.end_date = val[1]
  } else {
    searchForm.start_date = ''
    searchForm.end_date = ''
  }
}

// 处理单据日期变化
const handleSlipDateChange = (val) => {
  if (val && val.length === 2) {
    searchForm.slipStart_date = val[0]
    searchForm.slipEnd_date = val[1]
  } else {
    searchForm.slipStart_date = ''
    searchForm.slipEnd_date = ''
  }
}

// const getPaymentStatusLabel = (status) => {
//   switch (status) {
//     case "1":
//       return '未收款'
//     case "2":
//       return '部分收款'
//     case "3":
//       return '已结清'
//   }
// }
const pageInfo = reactive({
  List: [],
  pages: 1,
  total: 0,
  pageNum: 1,
  pageSize: 10
})

const changePage = (pageNum) => {
  pageInfo.pageNum = pageNum
  selectInv()
}

const invoiceList = ref([])

//单据日期格式化
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
// 查询
const selectInv = async () => {
  const response = await axios.get("/api/sales/selectInvoiceRegisterList", {
    params: {
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
      ...searchForm
    }
  })
  if (response.data.code == 200) {
    console.log("selectInv", response.data)
    invoiceList.value = response.data.invoiceRegisterList.list
    pageInfo.total = response.data.invoiceRegisterList.total
    pageInfo.pages = response.data.invoiceRegisterList.pages
  } else {
    ElMessage.error(response.data.msg)
  }
}

// 客户对话框启用
const customerDialogVisible = ref(false)
/**
 * 打开客户选择弹窗
 */

const openCustomerDialog = () => {
  customerDialogVisible.value = true
}

// 客户选择
const handleSelectCustomer = (customers) => {
  console.log('已选择客户:', customers)
  if (customers && customers.length > 0) {
    const customer = customers[0]
    searchForm.customerCode = customer.code
    searchForm.customerName = customer.name
  }
  customerDialogVisible.value = false
}


// 销售员列表数据
const salesPersonList = ref([
])
//销售员
const selectStaff = async () => {
  const response = await axios.get('/api/sales/selectStaff')
  if (response.data.code == 5200) {
    console.log('12', response.data)
    salesPersonList.value = response.data.saleStaffList
  } else {
    ElMessage.error(response.data.msg)
    console.error('获取销售员列表失败：', response.data.message)
  }
}

// 选中行
const selectedRows = ref([])

// 重置
const resetSearch = () => {
  searchForm.start_date = ''
  searchForm.end_date = ''
  searchForm.slipStart_date = ''
  searchForm.slipEnd_date = ''
  searchForm.salesSlipCode = ''
  searchForm.customerCode = ''
  searchForm.workNumber = ''

  dateRange.value = []
  inDateRange.value = []

  // 重置客户显示
  selectedCustomerDisplay.value = ''

}

const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 删除单个
const del = async (row) => {
  await ElMessageBox.confirm(
    `确定要删除 ${row.invoiceNumber} 吗？与${row.invoiceNumber}相关的记录也会被删除！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  );

  // 使用查询参数方式传递
  const response = await axios.post('/api/sales/deleteInv', null, {
    params: {
      invoiceNumber: [row.invoiceNumber]
    },
    paramsSerializer: {
      indexes: null 
    }
  });

  if (response.data.code == 200) {
    ElMessage.success('删除成功');
    selectInv();
  } else {
    ElMessage.error('删除失败: ' + response.data.message);
  }
};

// 批量删除
const batchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的发票');
    return;
  }

  // 显示确认对话框
  await ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个发票吗？删除中有相同发票号的也会被删除`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  );

  // 获取选中行的发票编号
  const invoiceNumbers = selectedRows.value.map(row => row.invoiceNumber);

  // 使用查询参数方式传递
  const response = await axios.post('/api/sales/deleteInv', null, {
    params: {
      invoiceNumber: invoiceNumbers
    },
    paramsSerializer: {
      indexes: null 
    }
  });

  if (response.data.code == 200) {
    ElMessage.success('删除成功');
    selectInv();
  } else {
    ElMessage.error('删除失败: ' + response.data.message);
  }
};

onMounted(() => {
  selectInv()
  selectStaff()
})


</script>

<style scoped>
.invoice-record-page {
  padding: 20px;
  background-color: white;
  min-height: 100vh;
}

.search-section {
  background: white;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;

}

.column-settings {
  margin-bottom: 15px;
  text-align: right;
}

.action-bar {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
  flex-wrap: wrap;
  background: white;
  padding: 10px;
  border-radius: 8px;
  float: right;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;

}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 响应式 */
@media (max-width: 768px) {

  .search-section,
  .action-bar {
    flex-direction: column;
    gap: 10px;
  }

  .table-container {
    overflow-x: auto;
  }
}
</style>